package com.uzai.console.service.alarm.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.BaseEntity;
import com.uzai.common.enums.SysMsgTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.alarm.alarmmsg.AlarmMsgQuery;
import com.uzai.console.entity.AlarmContacter;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.es.EsAlarmMsg;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.mapper.AlarmContacterMapper;
import com.uzai.console.service.alarm.AlarmMsgService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.vo.alarm.alarmcontacter.AlarmContacterInfoVo;
import com.uzai.console.vo.alarm.alarmmsg.AlarmMsgVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.analysis.solvers.BaseUnivariateSolver;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 报警消息记录查询
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class AlarmMsgServiceImpl implements AlarmMsgService {

    Logger logger = LoggerFactory.getLogger(AlarmMsgServiceImpl.class);

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private AlarmContacterMapper alarmContacterMapper;

    /**
     * 查询报警消息记录列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alarmMsgQuery
     * @return null
     */
    public Page<AlarmMsgVo> findAlarmMsgList(AlarmMsgQuery alarmMsgQuery){
        //新建返回到页面的LIST对象
        List<AlarmMsgVo> alarmMsgVoList = new ArrayList<>();

        //执行分页查询对象
        Page<AlarmMsgVo> page = new Page<>();
        alarmMsgQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(alarmMsgQuery.getMerId())));

        //报警类型
        if(alarmMsgQuery.getAlarmType() != null){
            boolQuery_and.must(QueryBuilders.termQuery("alarmType", alarmMsgQuery.getAlarmType()));
        }

        //机器人唯一id列表
        if(alarmMsgQuery.getDeviceUniqueIdList() != null && alarmMsgQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", alarmMsgQuery.getDeviceUniqueIdList()));
        }

        //紧急联系人id列表
        if(alarmMsgQuery.getContacterId() != null){
            //分词
            boolQuery_and.must(QueryBuilders.matchQuery("alarmContacters", alarmMsgQuery.getContacterId()));
        }

        //事件消息类型
        if(alarmMsgQuery.getMsgType() != null){
            boolQuery_and.must(QueryBuilders.termQuery("msgType", alarmMsgQuery.getMsgType()));
        }

        //查询开始时间
        if(alarmMsgQuery.getQueryStartTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("createTime").gte(alarmMsgQuery.getQueryStartTime()));
        }

        //查询结束时间
        if(alarmMsgQuery.getQueryEndTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("createTime").lte(alarmMsgQuery.getQueryEndTime()));
        }

        //消息内容
        if(StringUtils.isNotBlank(alarmMsgQuery.getMessage())){
            boolQuery_or.should(QueryBuilders.matchQuery("message", alarmMsgQuery.getMessage()));
            boolQuery_or.should(QueryBuilders.termQuery("message.raw", alarmMsgQuery.getMessage()));
        }

        //高亮字段
        String highlightField = null;

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(EsIndexName.UZAI_ALARM_MSG, searchSourceBuilder, alarmMsgQuery.getSize(), alarmMsgQuery.getFromIndex(), null, null, highlightField, alarmMsgQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                EsAlarmMsg esAlarmMsg  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsAlarmMsg.class);
                if(esAlarmMsg != null){
                    AlarmMsgVo alarmMsgVo = new AlarmMsgVo();
                    BeanUtils.copyProperties(esAlarmMsg, alarmMsgVo);
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(esAlarmMsg.getDeviceUniqueId(), esAlarmMsg.getDeviceType(), esAlarmMsg.getMerId());
                    if(device != null){
                        alarmMsgVo.setDeviceId(device.getDeviceId());
                        alarmMsgVo.setDeviceName(device.getDeviceName());
                        alarmMsgVo.setDeviceRemark(device.getDeviceRemark());
                    }
                    if(alarmMsgVo.getMsgType() != null){
                        SysMsgTypeEnum sysMsgTypeEnum = SysMsgTypeEnum.getById(alarmMsgVo.getMsgType());
                        if(sysMsgTypeEnum != null){
                            alarmMsgVo.setMsgTypeName(sysMsgTypeEnum.getDesc());
                        }
                    }
                    try {
                        if(StringUtils.isNotBlank(alarmMsgVo.getAlarmContacters())){
                            List<Long> contacterIdList = JSONObject.parseArray(alarmMsgVo.getAlarmContacters(),Long.class);
                            if(contacterIdList != null && contacterIdList.size() > 0){
                                List<String> contacterNameList = new ArrayList<>();
                                for(Long contacterId : contacterIdList){
                                    AlarmContacter alarmContacter = alarmContacterMapper.selectById(contacterId, alarmMsgQuery.getMerId());
                                    if(alarmContacter != null){
                                        contacterNameList.add(alarmContacter.getName());
                                    }
                                }
                                alarmMsgVo.setAlarmContacterNameList(contacterNameList);
                            }
                        }
                    }catch (Exception e){

                    }

                    alarmMsgVoList.add(alarmMsgVo);
                }
            }
        }

        //返回到页面分页对象
        page.setRecords(alarmMsgVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }
}
